import express from 'express';
import sql from '../../sql.js';
import fs from 'node:fs';
const router = express.Router();
import multer from'multer';

// 查询本地文件
router.post('/searchFile', async (req, res) => {
    let page = parseInt(req.body.page) || 1;
    const pageSize = parseInt(req.body.pageSize) || 10;
    let offset = (page - 1) * pageSize;
    const fileId = req.body.fileId;
    const name = req.body.name;
    const categoryId = req.body.categoryId;
    let files;

    let query = 'SELECT * FROM file';
    let params = [];
    if (fileId || name || categoryId) {
        query += ' WHERE ';
        if (fileId) {
            query += 'ID = ?';
            params.push(fileId);
        }
        if (name) {
            if (params.length > 0) query += ' AND ';
            query += 'file_name LIKE ?';
            params.push(`%${name}%`);
        }
        if (categoryId) {
            if (params.length > 0) query += ' AND ';
            query += 'category_id = ?';
            params.push(categoryId);
        }
    }
    query += ` LIMIT ? OFFSET ?`;
    params.push(pageSize, offset);

    try {
        [files] = await sql.query(query, params);
        if (files.length === 0 && page > 1) {
            page = page - 1
            offset = (page - 1) * pageSize;
            params[params.length - 1] = offset;
            const [data] = await sql.query(query, params);
            files = data;
         }
        if (files.length > 0) {
            let params = [];
            const totalCountQuery = 'SELECT COUNT(*) AS total FROM file';
            if (fileId || name || categoryId) {
                let totalCountWhereQuery = totalCountQuery + ' WHERE ';
                if (fileId) {
                    totalCountWhereQuery += 'ID = ?';
                    params.push(fileId);
                }
                if (name) {
                    if (params.length > 1) totalCountWhereQuery += ' AND ';
                    totalCountWhereQuery += 'file_name LIKE ?';
                    params.push(`%${name}%`);
                }
                if (categoryId) {
                    if (params.length > 1) totalCountWhereQuery += ' AND ';
                    totalCountWhereQuery += 'category_id = ?';
                    params.push(categoryId);
                }
                const [totalCountData] = await sql.query(totalCountWhereQuery, params);
                const total = totalCountData[0].total;
                const totalPages = Math.ceil(total / pageSize);
                res.send({
                    status: 'success',
                    message: '文件查询成功',
                    data: files,
                    pagination: {
                        currentPage: page,
                        pageSize: pageSize,
                        totalCount: total,
                        totalPages: totalPages
                    }
                });
            } else {
                const [totalCountData] = await sql.query(totalCountQuery);
                const total = totalCountData[0].total;
                const totalPages = Math.ceil(total / pageSize);
                res.send({
                    status: 'success',
                    message: '文件查询成功',
                    data: files,
                    pagination: {
                        currentPage: page,
                        pageSize: pageSize,
                        totalCount: total,
                        totalPages: totalPages
                    }
                });
            }
        } else {
            res.send({
                status: 'error',
                message: '未找到文件',
                errorCode: 404
            });
        }
    } catch (error) {
        console.error('查询错误：', error);
        res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }
});
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 设置文件存储的目录
        cb(null, 'uploads');
    },
    filename: function (req, file, cb) {
        // 设置文件名
        cb(null, Date.now() + '-' + file.originalname);
    }
});

const upload = multer({ storage: storage });

// 中间件用于处理文件上传错误
const handleUploadError = (err, req, res, next) => {
    if (err) {
        // 如果 multer 处理文件上传时出现错误，删除已上传的文件（如果有）
        if (req.file && fs.existsSync(req.file.path)) {
            fs.unlinkSync(req.file.path);
        }
        return res.send({
            status: 'error',
            message: '文件上传错误',
            errorCode: 400
        });
    }
    next();
};

// 上传文件接口
router.post('/upload', upload.single('file'), handleUploadError, async (req, res) => {
    const filePath = req.file.path;
    const fileName = filePath.split('\\').pop();
    const fileFormat = req.file.mimetype.split('/')[1];
    const categoryId = req.body.categoryId || 1;

    // 获取文件大小
    const stats = fs.statSync(filePath);
    const fileSizeInBytes = stats.size;
    const fileSizeInMB = (fileSizeInBytes / (1024 * 1024)).toFixed(2) + "MB";

    const query = 'INSERT INTO file (address, file_name, file_format, category_id, size) VALUES (?,?,?,?,?)';
    try {
        await sql.query(query, [filePath, fileName, fileFormat, categoryId, fileSizeInMB]);
        res.send({
            status: 'success',
            message: '文件上传成功',
            data: {
                filePath: filePath,
                fileName: fileName,
                fileFormat: fileFormat,
                categoryId: categoryId,
                size: fileSizeInMB
            }
        });
    } catch (error) {
        console.error('上传错误：', error);
        // 如果数据库插入操作出现错误，删除已上传的文件并返回错误响应
        if (req.file && fs.existsSync(req.file.path)) {
            fs.unlinkSync(req.file.path);
        }
        res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }
});


// 修改文件分类
router.put('/updateFileCategory', async (req, res) => {
    const fileIds = req.body.fileIds;
    const newCategoryId = req.body.newCategoryId;
    if (!fileIds) {
        return res.send({
            status: 'error',
            message: '缺少必要参数',
            errorCode: 400
        });
    }
    const placeholders = fileIds.map(() => '?').join(',');
    const query = `UPDATE file SET category_id = ? WHERE id IN (${placeholders})`;
    try {
        await sql.query(query, [newCategoryId,...fileIds]);
        res.send({
            status: 'success',
            message: '文件分类修改成功'
        });
    } catch (error) {
        console.error('修改错误：', error);
        res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }
});

// 删除文件
router.delete('/deleteFile', async (req, res) => {
    const fileIds = req.body.fileIds;
    if (!fileIds || fileIds.length === 0) {
        return res.send({
            status: 'error',
            message: '缺少必要参数',
            errorCode: 400
        });
    }

    // 先查询文件路径
    const filePathsPromises = fileIds.map(fileId => {
        const filePathQuery = 'SELECT address FROM file WHERE id =?';
        return sql.query(filePathQuery, [fileId]).then(results => results[0][0].address || null );
    });
    const filePaths = await Promise.all(filePathsPromises);
    // 删除数据库中的数据
    const placeholders = fileIds.map(() => '?').join(',');
    const deleteQuery = `DELETE FROM file WHERE id IN (${placeholders})`;
    try {
        await sql.query(deleteQuery, fileIds);
    } catch (error) {
        console.error('数据库删除错误：', error);
        return res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }

    // 删除文件系统中的文件
    const deletePromises = filePaths.map(filePath => {
        if (filePath && fs.existsSync(filePath)) {
            return new Promise((resolve, reject) => {
                fs.unlink(filePath, err => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve();
                    }
                });
            });
        } else {
            return Promise.resolve();
        }
    });
    try {
        await Promise.all(deletePromises);
        res.send({
            status: 'success',
            message: '文件删除成功'
        });
    } catch (error) {
        console.error('文件删除错误：', error);
        res.send({
            status: 'error',
            message: '服务器内部错误，文件删除部分出现问题',
            errorCode: 500
        });
    }
});

export default router;

